// pages/math/math.js
// 数学题目生成器
const MathGenerator = {
  // 一年级：10以内加减法
  grade1: {
    addition: () => {
      const a = Math.floor(Math.random() * 10) + 1;
      const b = Math.floor(Math.random() * (10 - a)) + 1;
      return {
        question: `${a} + ${b} = ?`,
        answer: a + b
      };
    },
    subtraction: () => {
      const a = Math.floor(Math.random() * 10) + 1;
      const b = Math.floor(Math.random() * a) + 1;
      return {
        question: `${a} - ${b} = ?`,
        answer: a - b
      };
    }
  },
  
  // 二年级：100以内加减法，乘法口诀
  grade2: {
    addition: () => {
      const a = Math.floor(Math.random() * 50) + 1;
      const b = Math.floor(Math.random() * 50) + 1;
      return {
        question: `${a} + ${b} = ?`,
        answer: a + b
      };
    },
    subtraction: () => {
      const a = Math.floor(Math.random() * 50) + 20;
      const b = Math.floor(Math.random() * a) + 1;
      return {
        question: `${a} - ${b} = ?`,
        answer: a - b
      };
    },
    multiplication: () => {
      const a = Math.floor(Math.random() * 9) + 1;
      const b = Math.floor(Math.random() * 9) + 1;
      return {
        question: `${a} × ${b} = ?`,
        answer: a * b
      };
    }
  },
  
  // 三年级：1000以内加减法，乘除法
  grade3: {
    addition: () => {
      const a = Math.floor(Math.random() * 500) + 1;
      const b = Math.floor(Math.random() * 500) + 1;
      return {
        question: `${a} + ${b} = ?`,
        answer: a + b
      };
    },
    subtraction: () => {
      const a = Math.floor(Math.random() * 500) + 100;
      const b = Math.floor(Math.random() * a) + 1;
      return {
        question: `${a} - ${b} = ?`,
        answer: a - b
      };
    },
    multiplication: () => {
      const a = Math.floor(Math.random() * 20) + 1;
      const b = Math.floor(Math.random() * 20) + 1;
      return {
        question: `${a} × ${b} = ?`,
        answer: a * b
      };
    },
    division: () => {
      const b = Math.floor(Math.random() * 10) + 2;
      const quotient = Math.floor(Math.random() * 10) + 1;
      const a = b * quotient;
      return {
        question: `${a} ÷ ${b} = ?`,
        answer: quotient
      };
    }
  }
};

Page({
  data: {
    grade: 1,
    gradeName: '一年级',
    gradeDesc: '基础运算练习',
    practiceList: [],
    currentType: '',
    currentQuestion: null,
    userAnswer: '',
    showResult: false,
    isCorrect: false,
    resultIcon: '',
    resultText: '',
    correctCount: 0,
    totalCount: 0,
    correctRate: 0,
    isFocused: false
  },

  onLoad(options) {
    const grade = parseInt(options.grade) || 1;
    this.initGrade(grade);
  },

  initGrade(grade) {
    const gradeConfig = {
      1: {
        name: '一年级',
        desc: '基础运算练习',
        practices: [
          { key: 'addition', name: '加法', icon: '➕' },
          { key: 'subtraction', name: '减法', icon: '➖' }
        ]
      },
      2: {
        name: '二年级',
        desc: '加减乘除练习',
        practices: [
          { key: 'addition', name: '加法', icon: '➕' },
          { key: 'subtraction', name: '减法', icon: '➖' },
          { key: 'multiplication', name: '乘法', icon: '✖️' }
        ]
      },
      3: {
        name: '三年级',
        desc: '综合运算练习',
        practices: [
          { key: 'addition', name: '加法', icon: '➕' },
          { key: 'subtraction', name: '减法', icon: '➖' },
          { key: 'multiplication', name: '乘法', icon: '✖️' },
          { key: 'division', name: '除法', icon: '➗' }
        ]
      }
    };

    const config = gradeConfig[grade] || gradeConfig[1];
    
    this.setData({
      grade: grade,
      gradeName: config.name,
      gradeDesc: config.desc,
      practiceList: config.practices
    });

    // 默认选择第一个练习类型
    if (config.practices.length > 0) {
      this.selectType({ currentTarget: { dataset: { type: config.practices[0].key } } });
    }
  },

  selectType(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      currentType: type,
      userAnswer: '',
      showResult: false,
      isFocused: true,
      correctCount: 0,
      totalCount: 0,
      correctRate: 0
    });
    // 每次选择类型时重新生成题目（确保随机）
    this.generateQuestion();
  },

  generateQuestion() {
    const gradeKey = `grade${this.data.grade}`;
    const generator = MathGenerator[gradeKey];
    
    if (generator && generator[this.data.currentType]) {
      // 每次生成题目时都是随机的（MathGenerator 内部使用 Math.random）
      const question = generator[this.data.currentType]();
      this.setData({
        currentQuestion: question,
        userAnswer: '',
        showResult: false,
        isFocused: true
      });
    }
  },

  onAnswerInput(e) {
    this.setData({
      userAnswer: e.detail.value
    });
  },

  submitAnswer() {
    const userAnswer = parseInt(this.data.userAnswer);
    const correctAnswer = this.data.currentQuestion.answer;
    const isCorrect = userAnswer === correctAnswer;

    const totalCount = this.data.totalCount + 1;
    const correctCount = isCorrect ? this.data.correctCount + 1 : this.data.correctCount;
    const correctRate = totalCount > 0 ? ((correctCount / totalCount) * 100).toFixed(1) : 0;

    this.setData({
      showResult: true,
      isCorrect: isCorrect,
      resultIcon: isCorrect ? '✅' : '❌',
      resultText: isCorrect ? '答对了！' : '答错了！',
      totalCount: totalCount,
      correctCount: correctCount,
      correctRate: correctRate,
      isFocused: false
    });

    // 更新记录
    const app = getApp();
    app.updateRecords('math', isCorrect);
  },

  nextQuestion() {
    this.generateQuestion();
  },

  restart() {
    this.setData({
      correctCount: 0,
      totalCount: 0,
      correctRate: 0,
      userAnswer: '',
      showResult: false,
      isFocused: true
    });
    this.generateQuestion();
  }
});

